<?php

namespace Pig\Controller;

class ActivityController extends BaseController {

    private $tca = array();
    public $tbName = CONTROLLER_NAME; 
    public $image_path = '';
    protected function init() {
        /*$type = array(
            array(1,'普通团'),
            array(2,'神秘团')
        );*/
        $type = I('request.type');
        $info = '';
        if(I('request.id')){
            $info = M($this->tbName)->find(I('request.id'));
            $type = $info['type'];
        }
        //商品
        $html = '';
        $goods = M('Goods')->where(array('deleted' => 0,'hidden' => 0))->Field('id as "0",name as "1"')->select();
        foreach ($goods as $key => $value) {
            $select = $value[0] == $info['goods_id']?'selected="selected"':'';
            $html .= '<option value="'.$value[0].'"'.$select.'>'.$value[1].'</option>';
        }
        //优惠券
        $coupon_html = '';
        $coupons = M('Coupon')->where(array('deleted' => 0,'type' => ['IN',[1,2]]))->select();
        foreach ($coupons as $key => $value) {
            $select = '';
            $coupon_html .= '<option value="'.$value['id'].'"'.$select.'>'.$value['name'].'('.($value['type'] ==1?'满减券:':'立减券:').$value['money'].')</option>';
        }
        $normal = ['leader_prices','group_coupon_id'];
        $secret = ['auto_group','cut_money'];
        //配置字段
        $this->tca = array(
            'type' => array(
                'label' => '活动类型',
                'type' => 'label',
                'data' => $type == 1?'普通团':'神秘团'
            ),
            'hidden' => array(
                'label' => '是否开启',
                'type' => $info?'label':'toggle_button',
                'data' => $info?($info['hidden']?'关闭':'开启'):0
            ),
            'auto_group' => array(
                'label' => '系统凑单',
                'type' => $info?'label':'toggle_button',
                'data' => $info?($info['auto_group']?'开启':'关闭'):0
            ),
            'goods_id' => array(
                'label' => '关联商品',
                'type' => 'select_tree',
                'data' => $html,
                'required' => true,
                'disabled' => $info?true:false
            ),
            'group_prices' => array(
                'label' => '团购价',
                'type' => 'text',
                'help' => '团购价为整数或精确到小数点后一位或两位的数值',
                'disabled' => $info?true:false
            ),
            'cut_money' => array(
                'label' => '团长立减金',
                'type' => 'text',
                'validate' => [
                    ['/^[0-9]+(.[0-9]{1,2})?$/','请输入正确的团长立减金'],
                ],
                'relation' => ['type',1],
                'help' => '团长立减金为整数或精确到小数点后一位或两位的数值',
                'disabled' => $info?true:false
            ),
            'leader_prices' => array(
                'label' => '团长价',
                'type' => 'text',
                'help' => '团购价为整数或精确到小数点后一位或两位的数值,团长不能再使用优惠券',
                'disabled' => $info?true:false
            ),
            'is_support_coupon' => array(
                'label' => '支持优惠券',
                'type' => $info?'label':'toggle_button',
                'data' => $info?($info['is_support_coupon']?'支持':'不支持'):0
            ),
            'limit' => array(
                'label' => '限购数量',
                'type' => 'text',
                'required' => true,
                'validate' => [
                    ['/\\d/','请输入正确的限购数量'],
                ],
                'help' => '限购数量为0或正整数,0表示不限购',
                'disabled' => $info?true:false
            ),
            'coupon_id' => array(
                'label' => '成团福利',
                'type' => $info?'label':'select_tree',
                'data' => $info?($info['coupon_id']?M('coupon')->where(array('id' => $info['coupon_id']))->getField('money').'元券':'无'):$coupon_html,
            ),
            'group_coupon_id' => array(
                'label' => '团长福利',
                'type' => $info?'label':'select_tree',
                'data' => $info?($info['group_coupon_id']?M('coupon')->where(array('id' => $info['group_coupon_id']))->getField('money').'元券':'无'):$coupon_html,
            ),
            'num' => array(
                'label' => '团购人数',
                'type' => 'text',
                'required' => true,
                'validate' => [
                    ['/\\d/','请输入正确的团长人数'],
                ],
                'help' => '团购人数',
                'disabled' => $info?true:false
            ),
            'total' => array(
                'label' => '拼团库存',
                'type' => 'text',
                'required' => true,
                'validate' => [
                    ['/\\d/','请输入正确的拼团库存'],
                ],
                'help' => '拼团库存为本次团购活动出售商品的数量，拼团库存为正整数,',
                'disabled' => $info?true:false
            ),
            'start' => array(
                'label' => '开始时间',
                'type' => 'text',
                'required' => true,
                'readonly' => true,
                'disabled' =>$info?true:false
                /*'type' => 'datetime',
                'required' => true,
                'mode' => 'date',
                'class' => 'date-min',
                'disabled' => ACTION_NAME == 'edit'?true:false*/
            ),
            'end' => array(
                'label' => '结束时间',
                'type' => 'text',
                'required' => true,
                'readonly' => true,
                'disabled' => $info?true:false
                /*'type' => 'datetime',
                'required' => true,
                'mode' => 'date',
                'class' => 'date-max',
                'disabled' => ACTION_NAME == 'edit'?true:false*/
            ),
            'expired' => array(
                'label' => '成团时效',
                'type' => 'text',
                'required' => true,
                'validate' => [
                    ['/\\d/','请输入正确的成团时间']
                ],
                'help' => '开团到满团的时间限制,单位为小时',
                'disabled' => $info?true:false
            ),
        );
        //根据团类型过滤掉不需要的字段
        if($type == 1){
            foreach ($normal as  $value) {
                unset($this->tca[$value]);
            }
        }else{
            foreach ($secret as  $value) {
                unset($this->tca[$value]);
            }
        }
    }

    /*
     * 列表页面
     */

    public function index() {
        $Obj = D($this->tbName); //实例化对象
        $category = I('request.category');
        if(!in_array($category,[1,2])){
            $this->error('您访问的页面不存在');
        }
        $Where = "deleted=0";
        if($category == 1){
            $Where .= " and type in (1,2)";
        }else{
             $Where .= " and type = 3";
        }
        /*关键字查询*/   
        if (I('request.name')!='') {
            $I_keyword = trim(I('request.name'));
            $Where .= " and (name like '%" . $I_keyword . "%')";
        }
        //控制分页显示条数
        if(I('post.limit_num')!=''){
            session('page_limit_num', I('post.limit_num'));
        }
        //控制列表排序
        $sorting = I('get.sorting') ? I('get.sorting') : 'id';
        $order = I('get.order') ? I('get.order') : 'desc';
        
        $limit_num = $_SESSION['page_limit_num'] ? $_SESSION['page_limit_num'] : 10;//客户列表默认10条
        
        $Page = new \Pig\Util\Page($list_sum = $Obj->where($Where)->count(), $offset = $limit_num); // 实例化分页类 传入总记录数和每页显示的记录数
        $list = $Obj
                ->where($Where)
                ->order($sorting.' '.$order)
                ->limit($Page->firstRow . ',' . $Page->listRows)
                ->select();
        $Plan = M('plan');
        $Group = M('group');
        foreach ($list as $key => &$value) {
            $value['info'] = $Plan
                            ->alias('a')
                            ->join(C('DB_PREFIX').'goods_info as b ON a.goods_info_id = b.id')
                            ->where(array('a.activity_id' => $value['id'],'a.deleted' => 0))
                            ->Field('a.group_price,b.assistant,b.cost_price,a.leader_price')
                            ->select();
            //成团数量
            $value['count'] = $Group->where(array('activity_id' => $value['id'],'complete_time' => array('gt',0)))->count()?:0;
        }
        //p($list);
        $this->assign('list', $list); // 赋值数据集
        $this->assign('page', $Page->show()); // 分页显示输出
        $this->display(); // 输出模板
    }

    /*
     * 编辑数据
     */

    public function edit() {
        $this->save();
    }

    /*
     * 保存数据
     */

    public function save() {
        try{
            $this->init();
            //编辑数据
            $id = I('request.id') ? I('request.id') : null;
            $info = M($this->tbName)->where('id = ' . $id)->find();
            if($info){
                if($info['type'] == 3){
                    $category = 2;
                }else{
                    $category = 1;
                }
            }else{
                $category = 1;
            }
            $this->assign('category',$category);
            if (IS_POST) {
                $type = I('request.type');
                if(!in_array($type, [1,2])){
                    $this->error('错误的团购类型');
                }
                /*页面原始必填项验证-start*/
                foreach ($_POST as $key => $val) {
                    if(@$this->tca[$key]['required'] && !preg_match('/\S/', $val)){
                        $this->error($this->tca[$key]['label'] . '*是必填项!');
                    }
                    //数据验证
                    if(isset($this->tca[$key]['validate'])){
                        if($_POST[$this->tca[$key]['relation'][0]] == $this->tca[$key]['relation'][1]){
                            foreach ($this->tca[$key]['validate'] as $value) {
                                if(!preg_match($value[0], $val)){
                                    $this->error($value[1]);
                                }
                            }
                        }
                    }
                }
                /*存在规格*/
                if(isset($_POST['info_id'])){
                    //根据团类型判断是否需要检测团长价
                    if($type == 2){
                        foreach ($_POST['group_price'] as $key => $value) {
                            if(!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $value) || !preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $_POST['leader_price'][$key])){
                                $this->error('请输入正确的团购价或团长价');
                            }   
                        }
                    }else{
                        foreach ($_POST['group_price'] as $key => $value) {
                            if(!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $value)){
                                $this->error('请输入正确的团购价');
                            } 
                        } 
                    }
                }else{
                    //根据团类型判断是否需要检测团长价
                    if($type == 2){
                        if(!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $_POST['group_prices']) || !preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $_POST['leader_prices'])){
                                $this->error('请输入正确的团购价或团长价');
                            } 
                    }else{
                        if(!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $_POST['group_prices'])){
                            $this->error('请输入正确的团购价');
                        }
                    }
                }
                $Obj = D($this->tbName);
                $Obj->startTrans();
                $result = $Obj->create();
                if (!$result) {
                    $this->error($Obj->getError());
                } else { 
                    $Obj->start = strtotime($Obj->start);
                    $Obj->end = strtotime($Obj->end);
                    if(!isset($_POST['hidden'])){
                        $Obj->hidden = 1;
                    }  
                    if(isset($_POST['auto_group'])){
                        $Obj->auto_group = 1;
                    }
                    if(isset($_POST['is_support_coupon'])){
                        $Obj->is_support_coupon = 1;
                    }
                    $Obj->type = $type;
                    $Goodsinfo = M('goods_info');
                    $Obj->crdate = time();
                    $Obj->tstamp = time();
                    $id = $Obj->add();
                    if(!$id){
                        debug($Obj->_sql());
                        $this->error('添加失败');
                        exit;
                    }
                    if($_POST['info_id']){
                        foreach ($_POST['info_id'] as $key => $value) {
                            $plan_data = [
                                'activity_id' => $id,
                                'goods_info_id' => $value,
                                'group_price' => $_POST['group_price'][$key],
                            ];
                            if($type == 2){
                                $plan_data['leader_price'] = $_POST['leader_price'][$key]; 
                            }
                            $flag = M('plan')->add($plan_data);
                            if(!$flag){
                                debug(M('plan')->sql());
                                $this->error('添加失败');
                            }
                        }
                    }else{
                        $plan_data = [
                            'activity_id' => $id,
                            'goods_info_id' => $Goodsinfo->where(array('goods_id' => $_POST['goods_id'],'deleted' => 0))->getField('id'),
                            'group_price' => $_POST['group_prices']
                        ];
                        if($type == 2){
                            $plan_data['leader_price'] = $_POST['leader_prices']; 
                        }
                        $flag = M('plan')->add($plan_data);
                        if(!$flag){
                            debug(M('plan')->sql());
                            $this->error('添加失败');
                        }
                    }
                    $message = '添加成功!';   
                }
                //多文件上传 end ************************************
                $Obj->commit();
                $this->success($message,U(CONTROLLER_NAME.'/index?category=1'));
            }
            if($info){
                $info['start'] = date('Y-m-d H:i:s',$info['start']);
                $info['end'] = date('Y-m-d H:i:s',$info['end']);
                $count = M('plan')->where(array('activity_id' => $info['id']))->count();
                if($count = 1){
                    $info['group_prices'] = M('plan')->where(array('activity_id' => $info['id']))->getField('group_price');
                    $info['leader_prices'] = M('plan')->where(array('activity_id' => $info['id']))->getField('leader_price');
                }
                $this->getGoodsInfo();
            }else{
                $this->assign('html','');
            }
            parent::autoFields($this->tca, $info);
            $this->display('info');
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->error('保存失败');
        }
    }

    /*根据商品获取商品详情*/
    public function getGoodsInfo(){
        $goods_id = I('param.goods_id');
        $info = '';
        if(I('request.id')){
            $info = M($this->tbName)->find($id);
            $goods_id = $info['goods_id'];
            $Plan = M('plan');
        }
        $html = '';
        //获取所有该品牌所有的机型
        $Obj = M('goods_info');
        $where = array('deleted' => 0,'goods_id' => $goods_id);
        $goods_info = $Obj->where($where)->select();
        $type = M('Goods')->where(array('id' => $goods_id))->getField('type');
        $html = '';
        if($type){
            $group_type = I('param.type');
            if($info){
                $group_type = $info['type'];
            }
            $html = '<div class="ass"><div class="controls"><div class="propertyTable '.($group_type == 1?'group':'').'"><div class="tabHead clearfix"><span>规格名称</span><span>商品编码</span><span>零售价</span><span>分销价</span><span>成本价</span><span>团购价</span>';
            if($group_type == 2){
                $html .= '<span class="leader">团长价</span>';
            }
            $html .= '</div><div class="tabBody">';
            foreach ($goods_info as $key => $value) {
                $html .= '<div class="item clearfix">';
                $html .= '<input type="hidden" name="info_id[]" value="'.$value['id'].'" />';
                $html .= '<span>'.$value['assistant'].'</span>';
                $html .= '<span>'.$value['sku'].'</span>';
                $html .= '<span>'.$value['sale_price'].'</span>';
                $html .= '<span>'.$value['distribution_price'].'</span>';
                $html .= '<span>'.$value['cost_price'].'</span>';
                $html .= '<span>'.($info?$Plan->where(array('goods_info_id' => $value['id'],'activity_id' => $info['id']))->getField('group_price'):'<input name="group_price[]" type="text" class="setInp"/>').'</span>';
                if($group_type == 2){
                    $html .= '<span class="leader">'.($info?$Plan->where(array('goods_info_id' => $value['id'],'activity_id' => $info['id']))->getField('leader_price'):'<input name="leader_price[]" type="text" class="setInp"/>').'</span>';
                }
                $html .= '</div>';
            }
            $html .= '</div></div></div>';
        }
        if(IS_AJAX){
            $usable_stock = $this->usableStock($goods_id);
            $this->ajaxReturn(array('html' => $html,'usable_stock' => $usable_stock));
        }else{
            $this->assign('html',$html);
        }
    }

    /**
     * 获取商品可用库存
     */
    public function usableStock($goods_id){
        //获取商品总库存
        $total_stock = M('goods_info')->where(array('goods_id' => $goods_id))->sum('stock');

        //获取订单占用库存数
        $order_free_stock = M('order')->where(array('goods_id' => $goods_id,'status' => array('IN',array(1,2))))->sum('num');

        $usable_stock = $total_stock - $order_free_stock;
        return $usable_stock;
    }

    /**
     * 修改活动状态
     */
    public function editStatus(){
        $id = I('request.id');
        $info = M($this->tbName)->find($id);
        $param = [
            'hidden' => 1,
            'tstamp' => time()
        ];
        if($info['hidden'] == 1){
            $param['hidden'] = 0;
        }
        M($this->tbName)->where(array('id' => $id))->save($param);
        echo 1;exit;
    }

    /**
     * 全局删除方法
     * @param null $id 需要删除的记录id
     */
    public function del() {
        $tbName = $this->tbName;

        $id = I('get.id');
        $is_del = $this->Config['is_del'];
        $rs = false;

        if ($is_del == 0) {
            if (M($tbName)->where('id = ' . $id)->delete()) {
                $rs = true;
            }
        } else {
            if (M($tbName)->where('id = ' . $id)->save(array('deleted' => 1))) {
                $rs = true;
            }
        }

        if ($rs) {
            $this->success('删除成功!', U(CONTROLLER_NAME . '/index', 'category=1'));
        } else {
            $this->error('删除失败，请稍后再试！');
        }
    }
}

?>